<template>
  <div class="user-profile">
    <a-card class="profile-card">
      <div class="profile-header">
        <h2>个人资料</h2>
        <a-button
          type="primary"
          @click="toggleEditMode"
          :loading="loading"
          class="edit-btn"
        >
          {{ isEditing ? "保存" : "编辑资料" }}
        </a-button>
      </div>

      <div class="profile-content">
        <!-- 头像区域 -->
        <div class="avatar-section">
          <a-upload
            :show-upload-list="false"
            :before-upload="beforeUpload"
            :custom-request="handleAvatarUpload"
            v-if="isEditing"
          >
            <div class="avatar-container">
              <img :src="userAvatar" alt="用户头像" class="avatar-img" />
              <div class="avatar-overlay">更换头像</div>
            </div>
          </a-upload>
          <div v-else class="avatar-container">
            <img :src="userAvatar" alt="用户头像" class="avatar-img" />
          </div>
        </div>

        <!-- 信息表单 -->
        <a-form
          :model="formData"
          layout="vertical"
          class="info-form"
          :disabled="!isEditing"
        >
          <a-form-item
            label="用户名"
            :rules="[{ required: true, message: '请输入用户名' }]"
          >
            <a-input
              v-model:value="formData.username"
              placeholder="请输入用户名"
            />
          </a-form-item>

          <a-form-item label="角色">
            <a-input :value="formatRole(formData.role)" disabled />
          </a-form-item>

          <a-form-item
            label="邮箱"
            :rules="[{ type: 'email', message: '请输入有效的邮箱地址' }]"
          >
            <a-input v-model:value="formData.Email" placeholder="请输入邮箱" />
          </a-form-item>

          <a-form-item
            label="联系电话"
            :rules="[
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' },
            ]"
          >
            <a-input
              v-model:value="formData.phone"
              placeholder="请输入联系电话"
            />
          </a-form-item>

          <a-form-item label="个人简介">
            <a-textarea
              v-model:value="formData.details"
              placeholder="请输入个人简介"
              :rows="4"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, toRaw, onMounted } from "vue";
import { message } from "ant-design-vue";
import { useUserStore } from "@/store/module/user";
import { uploadFile } from "@/api/upload";
import { handleUpdateUserInfo } from "@/api/user";

// 状态管理
const userStore = useUserStore();
const isEditing = ref(false);
const loading = ref(false);
const userAvatar = ref("");

// 表单数据
const formData = reactive({
  username: "",
  role: "",
  details: "",
  Email: "",
  phone: "",
});

// 初始化用户信息
const initUserInfo = () => {
  const userInfo = userStore.userInfo;
  if (userInfo) {
    userAvatar.value =
      userInfo.avatar ||
      "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png";
    formData.username = userInfo.username || "";
    formData.role = userInfo.role || "";
    formData.Email = userInfo.Email || "";
    formData.phone = userInfo.phone || "";
    formData.details = userInfo.details || "";
  }
};

onMounted(() => {
  initUserInfo();
});

// 切换编辑模式
const toggleEditMode = () => {
  if (isEditing.value) {
    saveUserInfo();
  } else {
    isEditing.value = true;
  }
};

// 保存用户信息
const saveUserInfo = async () => {
  loading.value = true;
  const data = {
    ...toRaw(formData),
    avatar: userAvatar.value,
    id: userStore.userInfo.id,
  };
  const res = await handleUpdateUserInfo(data);
  
  if (res.code === 200) {
    message.success("保存成功");
    // 1. 立即更新用户名并同步到Pinia
    userStore.username = formData.username;
    
    // 2. 移除setTimeout，直接使用最新用户名查询
    await userStore.getUserInfo(); // 此时getUserInfo会使用更新后的username
    initUserInfo(); // 立即刷新表单数据
    
    isEditing.value = false;
    loading.value = false;
  } else {
    message.error(res.response.data.msg);
    loading.value = false;
  }
};

// 格式化角色显示
const formatRole = (role) => {
  const roleMap = {
    admin: "管理员",
    user: "普通用户",
    editor: "编辑",
  };
  return roleMap[role] || role || "未知角色";
};

// 头像上传前校验
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    message.error("请上传 JPG 或 PNG 格式的图片");
    return false;
  }
  if (!isLt2M) {
    message.error("图片大小不能超过 2MB");
    return false;
  }
  return true;
};

// 处理头像上传（实际调用接口）
const handleAvatarUpload = async ({ file, onSuccess, onError }) => {
  try {
    // 创建FormData对象包装文件
    const formData = new FormData();
    formData.append("file", file); // 注意与后端接口字段名保持一致

    // 调用上传接口
    const response = await uploadFile(formData);

    // 上传成功后更新头像并通知组件
    userAvatar.value = response.data.url; // 假设接口返回图片URL
    onSuccess(); // 通知上传组件上传完成
    message.success(response.msg);
  } catch (error) {
    console.error("头像上传失败:", error);
    onError(error); // 通知上传组件上传失败
  }
};
</script>

<style scoped>
.user-profile {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 16px;
}

.profile-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.profile-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.profile-content {
  padding: 24px;
  display: flex;
  gap: 24px;
}

.avatar-section {
  flex-shrink: 0;
}

.avatar-container {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid #f5f5f5;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.info-form {
  flex: 1;
  min-width: 0;
}

@media (max-width: 768px) {
  .profile-content {
    flex-direction: column;
    align-items: center;
  }
}
</style>
